package com.zyz.friend.service.userexam.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zyz.common.core.constants.Constants;
import com.zyz.common.core.enums.ExamListType;
import com.zyz.common.core.enums.ResultCodeEnum;
import com.zyz.common.core.model.LoginUser;
import com.zyz.common.core.model.TableDataInfo;
import com.zyz.common.core.utils.ThreadLocalUtil;
import com.zyz.common.security.exception.ServiceException;
import com.zyz.common.security.service.TokenService;
import com.zyz.friend.manager.ExamCacheManager;
import com.zyz.friend.mapper.exam.ExamMapper;
import com.zyz.friend.mapper.userexam.UserExamMapper;
import com.zyz.friend.model.exam.Exam;
import com.zyz.friend.model.exam.dto.ExamQueryDTO;
import com.zyz.friend.model.exam.vo.ExamVO;
import com.zyz.friend.model.userexam.ExamEnterDTO;
import com.zyz.friend.model.userexam.UserExam;
import com.zyz.friend.service.userexam.IUserExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Value("${jwt.secret}")
    private String secret;

    @Override
    public void enter(String token, ExamEnterDTO examEnterDTO) {
        Long examId = examEnterDTO.getExamId();
        // 判断竞赛是否存在
        Exam exam = getExamById(examId);
        // 通过ThreadLocal拿到当前登录的用户id
        Long userId = ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
        // 如果用户已经报过名则不能重复报名
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if (userExam != null) {
            log.error("该用户已是参赛者，禁止用户再次报名参赛，用户id: {} 竞赛id: {}",userId, examId);
            throw new ServiceException(ResultCodeEnum.FAILED_USER_HAS_ENTER);
        }
        // 存入缓存redis
        examCacheManager.addUserExamCache(userId, examId);
        // 存入mysql
        userExam = new UserExam();
        userExam.setUserId(userId);
        userExam.setExamId(examId);
        int row = userExamMapper.insert(userExam);
        if (row != 1) {
            log.error("竞赛报名失败！用户id: {} 竞赛id: {}",userId, examId);
            throw new ServiceException(ResultCodeEnum.ERROR);
        }
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examDTO) {
        Long userId = ThreadLocalUtil.get(Constants.THREAD_LOCAL_USER_ID, Long.class);
        // 从redis中查询竞赛列表的数据
        Long total = examCacheManager.getListSize(ExamListType.USER_EXAM_LIST.getValue(),userId);
        List<ExamVO> examVOList = null;
        if (total == null || total <= 0) {
            // 从数据库中拿数据
            PageHelper.startPage(examDTO.getPageNumber(), examDTO.getPageSize());
            examVOList = userExamMapper.selectUserExamList(userId);
            total = new PageInfo<>(examVOList).getTotal();
            // 刷新redis中缓存
            examCacheManager.refreshCache(ExamListType.USER_EXAM_LIST.getValue(),userId);
        } else {
            examDTO.setType(ExamListType.USER_EXAM_LIST.getValue());
            examVOList = examCacheManager.getExamVOList(examDTO,userId);
            total = examCacheManager.getListSize(examDTO.getType(),userId);// 记得重新获取数量 以防redis中异常情况（的调用getExamVOList里面）
        }
        return CollectionUtil.isEmpty(examVOList)?
                TableDataInfo.empty():TableDataInfo.success(examVOList, total);

    }



    private Exam getExamById(Long examId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            log.error("竞赛不存在，竞赛id: {}", examId);
            throw new ServiceException(ResultCodeEnum.FAILED_EXAM_NOT_EXISTS);
        }
        return exam;
    }
}
